<template>
  <div>
    <side-title>基本信息</side-title>
    <div class="mt-2 px-8 py-4 text-sm">
      <div class="flex">
        <div class="w-1/2">
          <span>接口名称：</span>
          <span>{{ doc.summary }}</span>
        </div>
        <div class="w-1/2">
          <span>创建人：</span>
          <span>yueDongyang</span>
        </div>
      </div>
      <div class="flex mt-8">
        <div class="w-1/2">
          <span>状态：</span>
          <span>{{ statusName }}</span>
        </div>
        <div class="w-1/2">
          <span>更新时间：</span>
          <span>2024-01-01 14:34:23</span>
        </div>
      </div>
      <div class="flex mt-8">
        <div class="w-100">
          <span>接口路径：</span>
          <span>{{ doc.path }}</span>
        </div>
      </div>
    </div>

    <div v-if="headerList.length !== 0">
      <side-title>请求Header</side-title>
      <div class="mt-2 px-8 py-4 text-sm">
        <h3 class="text-xl">Header:</h3>
        <el-table :data="headerList" border>
          <el-table-column label="参数名称" prop="name" width="280" />
          <el-table-column label="是否必须" prop="required" width="100">
            <template slot-scope="scope">
              <div>
                <span v-if="scope.row.required">Y</span>
                <span v-else>N</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="例子" prop="default" width="196" />
          <el-table-column label="说明" prop="description" />
        </el-table>
      </div>
    </div>

    <div v-if="parameterList.length !== 0">
      <side-title>请求参数</side-title>
      <div class="mt-2 px-8 py-4 text-sm">
        <h3 class="text-xl">Query:</h3>
        <el-table :data="parameterList" border>
          <el-table-column label="参数名称" prop="name" width="280" />
          <el-table-column label="是否必须" prop="required" width="100">
            <template slot-scope="scope">
              <div>
                <span v-if="scope.row.required">Y</span>
                <span v-else>N</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="例子" prop="default" width="196" />
          <el-table-column label="说明" prop="description" />
        </el-table>
      </div>
    </div>

    <div v-if="doc.method !== 'GET' && bodyList.length !== 0">
      <side-title>请求Body</side-title>
      <div class="mt-2 px-8 py-4 text-sm">
        <h3 class="text-xl">Body:</h3>
        <el-table
          class="my-table"
          :data="bodyList"
          border
          fit
          :tree-props="{ children: 'children', hasChildren: 'hasExpand' }"
          row-key="id"
        >
          <el-table-column label="参数名称" prop="name" width="280" />
          <el-table-column label="类型" prop="type" width="140" />
          <el-table-column label="是否必须" prop="required" width="100" />
          <el-table-column label="例子" prop="default" width="100" />
          <el-table-column label="说明" prop="description" />
        </el-table>
      </div>
    </div>

    <side-title>返回数据</side-title>
    <div class="mt-2 px-8 py-4 text-sm">
      <el-tabs
        class="mt-2 response-tab"
        v-model="responseTabValue"
        type="card"
        editable
      >
        <el-tab-pane
          :key="item.statusCode"
          v-for="item in responses"
          :label="item.statusCode"
          :name="item.statusCode"
        >
          <div class="p-2">
            <div class="flex items-center mt-2">
              <span>HTTP状态码：</span>
              <el-input
                v-model="item.statusCode"
                size="small"
                style="width: 80px"
              ></el-input>
              <span class="ms-3">名称：</span>
              <el-input
                v-model="item.description"
                size="small"
                style="width: 180px"
              ></el-input>
              <span class="ms-3">内容格式：</span>
              <el-select size="small" v-model="item.responsesType">
                <el-option
                  v-for="item in responsesTypeOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </div>
            <div v-if="item.responsesType === 'application/json'">
              <el-table
                class="my-table"
                :data="item.bodyList"
                border
                fit
                :tree-props="{ children: 'children', hasChildren: 'hasExpand' }"
                row-key="id"
              >
                <el-table-column label="参数名称" prop="name" width="280" />
                <el-table-column label="类型" prop="type" width="140" />
                <el-table-column label="是否必须" prop="required" width="100" />
                <el-table-column label="例子" prop="default" width="100" />
                <el-table-column label="说明" prop="description" />
              </el-table>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
import {
  computed,
  onMounted,
  reactive,
  ref,
  toRef,
  watch,
  nextTick,
} from "@vue/composition-api";
import { useApiStore } from "@/store/api";
import JsonEdit from "@/components/BodyEdit/index.vue";
import SideTitle from "@/components/SideTitle/index.vue";
export default {
  components: {
    SideTitle,
    JsonEdit,
  },
  setup() {
    const apiStore = useApiStore();
    const doc = apiStore.doc
    const parameter = [
      {
        name: "repoId",
        required: "dasdasd",
        in: "query",
        schema: {
          type: "number",
        },
      },
      {
        name: "oldBranchId",
        required: true,
        in: "query",
        schema: {
          type: "number",
        },
      },
      {
        name: "newBranch",
        required: true,
        in: "query",
        schema: {
          type: "string",
        },
      },
    ];
    const parameterList = ref([])
    const headerList = ref([])
    if (apiStore.doc.parameters) {
      parameterList.value = apiStore.doc.parameters.filter((item) => item.in === "query")
      headerList.value = apiStore.doc.parameters.filter((item) => item.in === "header") 
    }

    let id = 1;
    function get(obj) {
      const list = [];
      Object.keys(obj).forEach((k) => {
        const dto = obj[k];
        if (["object"].includes(dto.type)) {
          list.push({
            id: id++,
            name: k,
            type: dto.type,
            description: dto.description,
            // hasExpand: true,
            children: get(dto.properties),
          });
        } else if (["array"].includes(dto.type)) {
          list.push({
            id: id++,
            name: k,
            type: dto.type,
            description: dto.description,
            // hasExpand: true,
            children:
              dto.items.type === "object"
                ? get(dto.items.properties)
                : [{ id: id++, type: dto.items.type }],
          });
        } else {
          list.push({
            id: id++,
            description: dto.description,
            type: dto.type,
            name: k,
          });
        }
      });
      return list;
    }
    const bodyList = ref([])
    if (
        apiStore.doc.requestBody &&
        apiStore.doc.requestBody.content &&
        apiStore.doc.requestBody.content["application/json"]
      ) {
        const content = apiStore.doc.requestBody.content["application/json"];
        if (content && content.schema && content.schema.properties) {
          bodyList.value = get(content.schema.properties)
        }
      }
    console.log(bodyList);

    const responseTabValue = ref("200");
    const responses = ref([]);
    const responsesTypeOptions = reactive([
      {
        label: "JSON",
        value: "application/json",
      },
      {
        label: "BLOB",
        value: "",
      },
    ]);
    const resJsonEditComponent = ref(null);
    onMounted(() => {
      const val = apiStore.doc
      if (val.responses) {
            responses.value = Object.entries(val.responses).map(([k, v]) => {
              if (v.content) {
                const key = Object.keys(v.content)[0];
                let responsesType = responsesTypeOptions.find(
                  (item) => item.value === key
                );
                if (!responsesType) {
                  responsesType = "application/json";
                } else {
                  responsesType = responsesType.value;
                }
                if (v.content[key] && v.content[key].schema) {
                  console.log(responsesType);
                  console.log(get(v.content[key].schema.properties));
                  return {
                    statusCode: k,
                    description: v.description,
                    responsesType,
                    schema: v.content[key].schema,
                    bodyList: get(v.content[key].schema.properties),
                  };
                } else {
                  return {
                    statusCode: k,
                    description: v.description,
                    bodyList: [],
                  };
                }
              } else {
                return {
                  statusCode: k,
                  description: v.description,
                  bodyList: [],
                };
              }
            });
            // nextTick(() => {
            //   const jsonEditList = [...resJsonEditComponent.value];
            //   responses.value.forEach((item) => {
            //     if (item.schema) {
            //       if (item.responsesType === "application/json") {
            //         const jsonEdit = jsonEditList.shift();
            //         jsonEdit.setBody(item.schema.properties);
            //       }
            //     }
            //   });
            // });
          }
    });

    const statusName = computed(() => {
      const status = apiStore.statusOptions.find(item => {
        return item.value === doc.statusId
      })
      if (status) {
        return status.label
      }
      return ''
    })
    return {
      doc,
      apiStore,
      parameter,
      parameterList,
      headerList,
      bodyList,
      responses,
      responseTabValue,
      responsesTypeOptions,
      resJsonEditComponent,

      statusName,
    };
  },
};
</script>

<style scoped>
.my-table >>> .el-table__expand-icon {
  transition: none;
}

.my-table >>> .el-table__expand-icon i {
  visibility: hidden;
}

.my-table >>> .el-table__expand-icon::after {
  content: "+";
  color: black;
  display: block;
  width: 12px;
  height: 12px;
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -8px;
  margin-top: -8px;
  z-index: 9999;
  line-height: 12px;
  text-align: center;
  border: 1px solid #e9e9e9;
  padding: 1px;
  box-sizing: content-box;
}
.my-table >>> .el-table__expand-icon--expanded::after {
  content: "-" !important;
  /* display: block;
    width: 12px;
    height: 12px;
    position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -6px;
    margin-top: -6px;
    z-index: 9999;
    line-height: 12px;
    text-align: center; */
  line-height: 8px;
  transform: rotate(90deg);
  transition: none;
}
</style>